<?php

namespace app\modules\mall\models;
use Yii;
use yii\db\ActiveRecord;
use Exception;
/**
 * 订单
 * @author XT
 */
class Order extends ActiveRecord {
    
    public static function db() {
        return Yii::$app->mall;
    }
    
    public static function tableName() {
        return 'yy_order';
    }
    /**
     * 创建订单
     * @param unknown $data
     */
    public function addOrder($data) {
        self::db()->createCommand()
        ->insert(self::tableName(), $data)->execute();
        return self::db()->getLastInsertID();
    }
    /**
     * 添加收件人信息
     * @param unknown $data
     */
    public function addReceiverInfo($data) {
        return self::db()->createCommand()
        ->insert('yy_receiver_info', [
            'uid'               => $data['uid'],
            'receiver_name'     => $data['receiver_name'],
            'receiver_address'  => $data['receiver_address'],
            'receiver_phone'    => $data['receiver_phone'],
            'receiver_country'  => $data['receiver_country'],
            'receiver_province' => $data['receiver_province'],
            'receiver_city'     => $data['receiver_city'],
            'receiver_town'     => $data['receiver_town'],
            'receiver_location' => $data['receiver_location'],
            'receiver_code'     => $data['receiver_code']
        ])->execute();
    }
    /**
     * 得到用户订单列表
     * @param unknown $data
     */
    public function getOrderList($orderid) {
        $sql = 'select * from ' . self::tableName() . " where order_id='{$orderid}'";
        return self::db()->createCommand($sql)->queryAll();
    }
    /**
     * 根据parent_order_id得到用户订单列表
     * @param unknown $data
     */
    public function getOrderListByPOid($parent_order_id) {
        $sql = 'select * from ' . self::tableName() . " where parent_order_id='{$parent_order_id}'";
        return self::db()->createCommand($sql)->queryAll();
    }
    /**
     * 分页显示order的id
     * @param unknown $data
     */
    public function getOrderIds($data) {
        $state  = $data['state'];
        $uid    = $data['uid'];
        $page   = $data['page'];
        $size   = $data['size'];
        $limit  = ($page - 1) * $size;
        
        if($state == 4) {
            //全部订单信息
            $sql = 'select distinct order_id from ' . self::tableName() . ' where is_delete=0 and uid=' . $uid . ' order by create_time desc limit ' . $limit . ', ' . $size;
        } else {
            //某种state的订单信息
            $sql = 'select distinct order_id from ' . self::tableName() . ' where is_delete=0 and state=' . $state . ' and uid=' . $uid . ' order by create_time desc limit ' . $limit . ', ' . $size;
        }
        return self::db()->createCommand($sql)->queryAll();
    }
    /**
     * 分页得到查询的order的id
     * @param unknown $data
     */
    public function getSearchOrderIds($data) {
        $uid        = $data['uid'];
        $page       = $data['page'];
        $size       = $data['size'];
        $limit      = ($page-1) * $size;
        $orderid    = $data['orderid'];
        $sql = 'select distinct order_id from ' . self::tableName() . ' where is_delete=0 and uid=' . $uid . " and order_id like '%{$orderid}%' order by modify_time desc limit " . $limit . ', ' . $size;
        return self::db()->createCommand($sql)->queryAll();
    }
    /**
     * 删除订单
     * @param unknown $data
     */
    public function deleteOrder($data) {
        return self::db()->createCommand()
        ->update(self::tableName(),
            [
                'is_delete'     => 1,
                'deal_time'     => time()
            ],
            [
                'order_id'  => $data['order_id'],
                'uid'       => $data['uid'],
                'state'     => $data['state']
            ]
        )->execute();
    }
    /**
     * 确认收货
     * @param unknown $data
     */
    public function receive($data) {
        $uid = $data['uid'];
        $order_id = $data['order_id'];
        $state = $data['state'];
        
        return self::db()->createCommand()
            ->update(self::tableName(), 
                [
                    'state'         => $data['state'],
                    'deal_time'     => time()
                ],
                [
                    'order_id'  => $data['order_id'],
                    'uid'       => $data['uid'],
                    'state'     => 2,
                    'is_delete' => 0
                ]
            )->execute();
    }
    /**
     * 提醒卖家发货
     * @param unknown $data
     */
    public function remindDelivery($data) {
        return self::db()->createCommand()
        ->update(self::tableName(),
            [
                'is_remind_delivery'    => 1
            ],
            [
                'order_id'  => $data['order_id'],
                'uid'       => $data['uid'],
                'state'     => 1,
                'is_delete' => 0
            ]
        )->execute();
    }
    /**
     * 取消订单
     * @param unknown $data
     */
    public function cancel($data) {
        $uid = $data['uid'];
        $order_id = $data['order_id'];
        $state = $data['state'];
        
        return self::db()->createCommand()
        ->update(self::tableName(),
            [
                'state'         => $data['state'],
                'deal_time'     => time(),
                'modify_time'   => time()
            ],
            [
                'order_id'  => $data['order_id'],
                'uid'       => $data['uid'],
                'state'     => 0,
                'is_delete' => 0
            ]
        )->execute();
    }
    /**
     * 得到订单详情
     * @param unknown $data
     */
    public function getOrderDetail($data) {
        $sql = 'select * from ' . self::tableName() . " where uid={$data['uid']} and is_delete=0 and order_id='{$data['orderid']}'";
        return self::db()->createCommand($sql)->queryAll();
    }
    /**
     * 修改订单的评论状态
     * @param unknown $order_id
     */
    public function setCommentState($order_id) {
        return self::db()->createCommand()
        ->update(self::tableName(),
            [
                'is_comment'     => 1,
            ],
            [
                'order_id'  => $order_id,
                'is_delete' => 0
            ]
        )->execute();
    }
    /**
     * 通过用户id，订单状态查询订单数
     * @param unknown $uid
     * @param unknown $state
     */
    public function getOrderNumByState($uid, $state) {
        $sql = 'select count(distinct order_id) from ' . self::tableName() . ' where is_delete=0 and uid=' . $uid . ' and state=' . $state;
        return self::db()->createCommand($sql)->queryScalar();
    }
    /**
     * 得到未评论的订单数
     * @param unknown $uid
     */
    public function getUncommentNum($uid) {
        $sql = 'select count(distinct order_id) from ' . self::tableName() . ' where state=3 and is_delete=0 and uid=' . $uid . ' and is_comment=0';
        return self::db()->createCommand($sql)->queryScalar();
    }
    /**
     * 分页得到未评论的order的id
     * @param unknown $data
     */
    public function getUncommentOrderIds($data) {
        $state  = $data['state'];
        $uid    = $data['uid'];
        $page   = $data['page'];
        $size   = $data['size'];
        $limit  = ($page - 1) * $size;
        
        $sql = 'select distinct order_id from ' . self::tableName() . ' where is_comment=0 and is_delete=0 and state=' . $state . ' and uid=' . $uid . ' order by create_time desc limit ' . $limit . ', ' . $size;
        return self::db()->createCommand($sql)->queryAll();
    } 
    /**
     * 判断用户当前订单是否存在
     * @param unknown $uid
     * @param unknown $orderid
     * @param unknown $goodsid
     */
    public function hasOrder($isComment=0, $uid, $orderid, $goodsid) {
        $sql = 'select count(*) from ' . self::tableName() . ' where is_delete=0 and is_comment=' . $isComment . ' and uid=' . $uid . " and order_id='{$orderid}' and goods_id='{$goodsid}'";;
        return self::db()->createCommand($sql)->queryScalar();
    }
    /**
     * 通过订单id判断订单是否存在
     * @param unknown $uid
     * @param unknown $orderid
     */
    public function hasOrderByOrderid($uid, $orderid) {
        $sql = 'select count(*) from ' . self::tableName() . ' where is_delete=0 and uid=' . $uid . " and order_id='{$orderid}'";
        return self::db()->createCommand($sql)->queryScalar();
    }
    /**
     * 得到用户设置的收件人信息
     * @param unknown $uid
     */
    public function getReceiverInfo($uid) {
        $sql = 'select * from yy_receiver_info where uid=' . $uid . ' limit 1';
        return self::db()->createCommand($sql)->queryOne();
    }
    /**
     * 修改收件人信息
     * @param unknown $data
     */
    public function updateReceiverInfo($data) {
        return self::db()->createCommand()
        ->update('yy_receiver_info', 
            [
                'receiver_name'     => $data['receiver_name'],
                'receiver_address'  => $data['receiver_address'],
                'receiver_phone'    => $data['receiver_phone'],
                'receiver_country'  => $data['receiver_country'],
                'receiver_province' => $data['receiver_province'],
                'receiver_city'     => $data['receiver_city'],
                'receiver_town'     => $data['receiver_town'],
                'receiver_location' => $data['receiver_location'],
                'receiver_code'     => $data['receiver_code'],
                'modify_time'       => date("Y-m-d H:i:s")
            ],[
                'uid'               => $data['uid'],
                'id'                => $data['id']
            ]
        )->execute();
    }
    /**
     * 得到快递或物流信息
     * @param unknown $orderid
     */
    public function getLogisticsInfo($orderid) {
        $sql = "select * from yy_goods_package where order_id='{$orderid}'";
        return self::db()->createCommand($sql)->queryAll();
    }
    public function getOneLogisticsInfo($orderid) {
        $sql = "select * from yy_goods_package where order_id='{$orderid}' limit 1";
        return self::db()->createCommand($sql)->queryOne();
    }
    /**
     * 通过order表主键获取order订单信息
     * @param unknown $order_prk_id
     */
    public function getOrderInfoByPk($order_prk_id) {
        $sql = 'select goods_id, shop_id, shop_name, goods_name, skuid, picid, price, unit, num, size, color from yy_order where id=' . $order_prk_id . ' limit 1';
        return self::db()->createCommand($sql)->queryOne();
    }
    /**
     * 更改订单金钱相关信息
     * @param unknown $data
     */
    public function updateOrderPrice($data) {
        $total_price = $data['shippingPrice'] + $data['taxPrice'] + $data['totalPrice'];
        $commission_price = round($total_price * Yii::$app->params['commission_rate']);
        return self::db()->createCommand()
        ->update('yy_order',
            [
                'shipping_price'    => $data['shippingPrice'],
                'total_price'       => $total_price,
                'commission_price'  => $commission_price
            ],[
                'uid'               => $data['uid'],
                'order_id'          => $data['orderid']
            ]
        )->execute();
    }
    /**
     * 支付订单
     * @param unknown $orderid
     */
    public function payOrder($data) {
        return self::db()->createCommand()
        ->update(self::tableName(),
            [
                'state'     => $data['state'],
                'pay_type'  => $data['payType'],
                'pay_time'  => $data['payTime'],
                'transaction_number' => $data['transactionNumber'],
            ],[
                'state'     => 0,
                'order_id'  => $data['orderid']
            ]
        )->execute();
    }
    /**
     * 支付订单
     * @param unknown $orderid
     */
    public function payParentOrder($data) {
        return self::db()->createCommand()
        ->update(self::tableName(),
            [
                'state'     => $data['state'],
                'pay_type'  => $data['payType'],
                'pay_time'  => $data['payTime'],
                'transaction_number' => $data['transactionNumber'],
            ],[
                'state'             => 0,
                'parent_order_id'   => $data['orderid']
            ]
        )->execute();
    }
    /**
     * 存储支付宝异步返回参数
     * @param unknown $data
     */
    public function saveAlipayParams($data) {
        return self::db()->createCommand()
        ->insert('yy_alipay_notify', $data)->execute();
    }
    /**
     * 存储微信异步返回参数
     * @param unknown $data
     */
    public function saveWxpayParams($data) {
        return self::db()->createCommand()
        ->insert('yy_wxpay_notify', $data)->execute();
    }
    /**
     * 通过子订单id，用户id获取订单详情
     * @param unknown $orderid
     * @param unknown $uid
     */
    public function getOrderInfoByOId($orderid, $uid) {
        $sql = 'select order_id, parent_order_id, goods_name, total_price from ' . self::tableName() . " where state=0 and order_id='{$orderid}' and uid='{$uid}'";
        return self::db()->createCommand($sql)->queryAll();
    }
    /**
     * 通过父订单id，用户id获取订单详情
     * @param unknown $parent_order_id
     * @param unknown $uid
     */
    public function getOrderInfoByPOId($parent_order_id, $uid) {
        $sql = 'select order_id, parent_order_id, goods_name, total_price from ' . self::tableName() . " where state=0 and parent_order_id='{$parent_order_id}' and uid='{$uid}'";
        return self::db()->createCommand($sql)->queryAll();
    }
    /**
     * 更新商户可提现金钱余额
     * @param unknown $shopId
     * @param unknown $price
     */
    public function updateShopAmount($shopId, $price) {
        $sql = "update yy_shop_info set account_amount=account_amount+{$price} where sid={$shopId}";
        return self::db()->createCommand($sql)->execute();
    }
    /**
     * 得到商户余额
     * @param unknown $shopId
     */
    public function getShopAmount($shopId) {
        $sql = 'select account_amount from yy_shop_info where sid=' . $shopId;
        return self::db()->createCommand($sql)->queryScalar();
    }
    /**
     * 插入物流运输明细
     * @param unknown $data
     */
    public function insertLogisticsDetail($data) {
        return self::db()->createCommand()
        ->insert('yy_logistics_detail', $data)->execute();
    }
    /**
     * 删除物流运输明细
     * @param unknown $logistics_num
     */
    public function deleteLogisticsDetail($logistics_num) {
        return self::db()->createCommand()->delete('yy_logistics_detail', ['logistics_num'=>$logistics_num])->execute();
    } 
    /**
     * 通过物流号获取物流详细信息
     * @param unknown $logistics_num
     */
    public function getLogisticsDetailByNum($logistics_num, $logistics_code) {
        $sql = 'select * from yy_logistics_detail where logistics_num=\'' . $logistics_num . '\' and logistics_name=\'' . $logistics_code . '\' order by time desc';
        return self::db()->createCommand($sql)->queryAll();
    }
    /**
     * 得到最新一条物流详细信息
     * @param unknown $logistics_num
     */
    public function getOneLogisticsDetailByNum($logistics_num, $logistics_code) {
        $sql = 'select * from yy_logistics_detail where logistics_num=\'' . $logistics_num . '\' and logistics_name=\'' . $logistics_code . '\' order by time desc limit 1';
        return self::db()->createCommand($sql)->queryOne();
    }
}